<template>
  <div>
    <Verify
      :number="number"
      @success="success"
      mode="pop"
      captchaType="blockPuzzle"
      :imgSize="{ width: '330px', height: '155px' }"
      ref="verifys"
    ></Verify>

    <div class="wechat">
      <el-dialog
        v-model="dialogVisible"
        :title="Tips"
        :show-close="false"
        :close-on-click-modal="false"
        width="380px"
        center
        style="border-radius: 20px"
        :before-close="handleClose"
      >
        <div class="wechatbox" v-if="type == 'phone'">
          <div class="yanse"></div>
          <div class="inputbox">
            <div class="input">
              <input type="number" placeholder="手机号" v-model="phone" />
            </div>
            <div class="input" style="margin-top: 20px">
              <input type="text" placeholder="验证码" v-model="code" />
              <div class="sendcode click f-j-a-c" @click="sendcode">
                {{ !sendCheck ? "发送验证码" : "重新发送" + time }}
              </div>
            </div>
            <div class="querne f-j-a-c click" @click="getbindfont">确认</div>
            <div class="tishi">
              <span
                >温馨提示:
                <span style="color: #656f79"
                  >用户需绑定真实手机号，系统将同步数据
                  DESAI将对用户隐私信息给予严格保密
                </span>
              </span>
            </div>
          </div>
        </div>
        <div
          class="wechatbox f-j-a-c"
          style="width: 100%"
          v-else-if="type == 'wechat'"
        >
          <div class="erwei_item f-j-a-c">
            <vue-qr
              @clean="clean"
              v-if="qrcodeVal"
              :text="qrcodeVal"
              :size="200"
            ></vue-qr>
          </div>
          <div class="f-a-c denglu">
            <svg-icon name="icon-weixin"></svg-icon> <span>微信扫码绑定</span>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import CryptoJS from "crypto-js";
import vueQr from "vue-qr/src/packages/vue-qr.vue";

import { bindfont, sendsms, bindwcchat, tick ,userinfo} from "@/axios/api.js";
import Verify from "@/components/verifition/Verify.vue";
import VueDragVerify from "vue-drag-verify";

import { useRouter } from "vue-router";
import {
  computed,
  defineComponent,
  onMounted,
  reactive,
  toRefs,
  getCurrentInstance,
  onUnmounted,
  ref,
} from "vue";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";

export default defineComponent({
  components: {
    Verify,
    vueQr,
  },
  props: {
    type: {
      // 判断是微信扫码还是手机号绑定
      type: String,
      default: "",
    },
    uniid: {
      // 微信id
      type: String,
      default: "",
    },
  },
  setup(props, { attrs, slots, emit }) {
    let userInfo = computed(() => {
      return store.state.minUserInfo;
    });

    const verifys = ref();

    const router = useRouter();
    const { proxy } = getCurrentInstance();
    let store = useStore();
    let data = reactive({
      qrcodeVal: "",
      dialogVisible: false,
      Tips: "",
      number: "",
      phone: "", //手机
      code: "", //验证码
      time: 120,
      sendCheck: false,
      uniid: "",
      times: 3000,
      timecode: "",
    });
    // 获取二维码
    let gettick = () => {
      tick().then((res) => {
        let info = JSON.parse(res.data.data);
        data.qrcodeVal = info.url;
        data.timecode = setInterval(() => {
          getbindwcchat(res.data.scene_str);
        }, data.times);
      });
    };
    // 绑定
    let getbindfont = () => {
      let datas = {};
      datas.phone = data.phone;
      datas.code = data.code;
      datas.unionid = data.uniid;
      bindfont({ ...datas })
        .then((res) => {
          emit("loginSuccess", res);
          setTimeout(() => {
            handleClose();
          }, 100);
        })
        .catch((err) => {
          return ElMessage.error(err.msg);
        });
    };
    // 检查是否绑定微信
    let getbindwcchat = (code) => {
      let id = "?code=" + code;
      bindwcchat({ id: id })
        .then((res) => {
          if (res.code == 0) {
            clearInterval(data.timecode);
            handleClose();
            getuserinfo()
            store.commit("setminToken", res.data.miniData.token);
            store.commit("saveminUserInfo", res.data.miniData.user);
            let userinfoold = userInfo.value;
            userinfoold.mininfo = res.data.miniData.user;
            store.commit("saveUserInfo", userinfoold);
            return ElMessage.success("绑定成功");
          } else if (res.code == 1) {
            return ElMessage.success("绑定失败");
          }
        })
        .catch((err) => {
          clearInterval(data.timecode);
        });
    };
    // 发送验证码
    let sendcode = () => {
      verifys._value.show();
    };
    let getuserinfo = () => {
      userinfo().then((res) => {
        let dataslist = res.data;
        dataslist.mininfo = store.state.minUserInfo;
        store.commit("saveUserInfo", dataslist);
        handleClose();
      });
    };
    let dialogClick = (id) => {
      data.dialogVisible = true;
      if (id) {
        data.uniid = id;
      }
    };
    let handleClose = () => {
      data.dialogVisible = false;
    };
    let encrypt = (word) => {
      const key = CryptoJS.enc.Utf8.parse("baoposhengerzim1");
      const IV = CryptoJS.enc.Utf8.parse("baoposhengerzim1");
      let srcs = CryptoJS.enc.Utf8.parse(word);
      var encrypted = CryptoJS.AES.encrypt(srcs, key, {
        iv: IV,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.ZeroPadding,
      });
      return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
    };
    // 用户通过了验证
    const success = (msg) => {
      // 发送验证码
      if (data.time == 120) {
        sendsms({
          clientUid: encrypt(data.phone),
          captchaVerification: msg.captchaVerification,
        })
          .then((res) => {
            if (res.code == 0 && data.sendCheck == false) {
              let time = setInterval(() => {
                data.time--;
                if (data.time == 0) {
                  clearTimeout(time);
                  data.sendCheck = false;
                  data.time = 120;
                }
              }, 1000);
              data.sendCheck = true;
              return ElMessage.success("验证码发送成功");
            }
          })
          .catch((err) => {
            console.log(err);
            data.sendCheck = true;

            data.time = err.data;

            let time = setInterval(() => {
              data.time--;
              if (data.time == 0) {
                clearTimeout(time);
                data.sendCheck = false;
                data.time = 120;
              }
            }, 1000);
            return ElMessage.error("发送失败");
          });
      } else {
        return ElMessage.error("验证码已发送,请等待倒计时结束");
      }
    };
    let clean = () => {
      console.log(123);
    };
    onMounted(() => {
      console.log(props.uniid);
      props.type == "wechat"
        ? (data.Tips = "绑定微信")
        : (data.Tips = "绑定手机号");
      if (props.type == "wechat") {
        gettick();
      }
    });
    onUnmounted(() => {});
    return {
      userInfo,
      getuserinfo,
      clean,
      getbindwcchat,
      gettick,
      encrypt,
      getbindfont,
      sendcode,
      verifys,
      success,
      handleClose,
      dialogClick,
      ...toRefs(data),
    };
  },
});
</script>
<style lang="scss" scoped>
.denglu {
  position: absolute;
  bottom: 8%;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
  margin-top: 21px;
  > span {
    margin-left: 10px;
    font-size: 14px;
    font-family: Microsoft YaHei-Regular, Microsoft YaHei;
    font-weight: 400;
    color: #000000;
  }
}
.erwei_item {
  position: relative;
  width: 260px;
  height: 260px;
  background: #ffffff;
  box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, 0.1);
  border-radius: 20px 20px 20px 20px;
  opacity: 1;
}
.querne {
  margin: 0 auto;
  margin-top: 40px;
  //   width: 380px;
  height: 48px;
  background: linear-gradient(90deg, #9ed8e6 0%, #a1f0c0 100%);
  border-radius: 10px 10px 10px 10px;
  font-size: 14px;
  font-family: Microsoft YaHei-Bold, Microsoft YaHei;
  font-weight: 700;
  color: #ffffff;
}
.tishi {
  margin: 0 auto;
  margin-top: 20px;
  > span {
    font-size: 14px;
    font-family: Microsoft YaHei-Regular, Microsoft YaHei;
    font-weight: 400;
    color: #ff425b;
  }
}
.input {
  position: relative;
  > input {
    padding: 0 20px;
    width: 100%;
    height: 48px;
    background: #f8fdfe;
    border-radius: 10px 10px 10px 10px;
    opacity: 1;
    border: 1px solid #64c8dc;
  }

  .sendcode {
    position: absolute;
    top: 4px;
    right: 5px;
    width: 96px;
    height: 40px;
    background: linear-gradient(90deg, #9ed8e6 0%, #a1f0c0 100%);
    border-radius: 10px 10px 10px 10px;
    opacity: 1;
    font-size: 14px;
    font-family: Microsoft YaHei-Regular, Microsoft YaHei;
    font-weight: 400;
    color: #ffffff;
  }
}
.inputbox {
  position: relative;
  z-index: 2;
}
.wechatbox {
  position: relative;
  //   height: 500px;
  background: #ffffff;
  border-radius: 20px 20px 20px 20px;
  opacity: 1;
}
::v-deep .el-dialog__title {
  font-size: 15px;
  font-family: Microsoft YaHei-Bold, Microsoft YaHei;
  font-weight: 700;
  color: #000000;
}
.yanse {
  position: absolute;
  top: 0;
  left: 0;
  width: 215px;
  height: 163px;
  background: rgba(100, 200, 220, 0.5);
  z-index: 0;
  filter: blur(190px);
}
</style>
